<?php

namespace app\middleware;

use think\Request;
use app\model\User;
use app\model\Role;
use app\model\Permission;

/**
 * rbac中间件
 */
class RBACAuth{
    public function handle(Request $request, \Closure $next, $requiredPermission = null){
        //  获取用户id
        $user_id = $request->user->id ?? null;
        if(!$user_id)
            return json([
                'code' => 401,
                'msg' => '未登录或身份过期'
            ], 401);
        
        //  获取用户id对应的角色id
        $role_id_array = User::find($user_id)->roles->column('id');
        if (empty($role_id_array)) {
            return json([
                'code' => 403,
                'msg' => '未被分配角色'
            ], 403);
        }

        //  获取角色id对应的权限id
        $permission_id_array = [];
        for($i=0; $i<count($role_id_array); $i++){
            $perm_id = Role::find($role_id_array[$i])->permissions->column('id');
            if (empty($perm_id)) {
                return json([
                    'code' => 403,
                    'msg' => '未被分配权限'
                ], 403);
            }
            $permission_id_array[$i] =  $perm_id;
        }
        $permission_id_array = array_values(array_unique(array_merge(...$permission_id_array)));    //  将二维数组打平为一维数组再去重

        //  获取权限id对应的权限标识
        $permission_names = [];
        for($i=0; $i<count($permission_id_array); $i++)
            $permission_names[$i] = Permission::where('id', $permission_id_array[$i])->value('name');

        /*
        print_r($permission_names);
        die;
        */

        if ($requiredPermission) {
            if (!in_array($requiredPermission, $permission_names)) {
                return json([
                    'code' => 403,
                    'msg' => '权限不足'
                ], 403);
            }
        }

        return $next($request);
    }
}